package cn.itcast.web.exception;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义的全局异常
 *   当控制器出现异常时候，自动去容器中查找HandlerExceptionResolver类型的对象。
 */
@Component
public class CustomException implements HandlerExceptionResolver {

    /**
     * 自定义异常处理逻辑
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 控制器类
     * @param ex 异常信息
     * @return
     */
    @Override
    public ModelAndView resolveException(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 打印异常到控制台
        ex.printStackTrace();

        // 返回
        ModelAndView mv = new ModelAndView("error");
        mv.addObject("errorMsg","系统忙，请联系管理员！" + ex.getMessage());
        return mv;
    }
}
